#!/bin/bash
# common functions

if [ "`whoami`" != "root" ] ; then
	echo "Must be root"
	exit 1
fi

RFS=${PWD}/rootfs-skeleton
export PATH=${PATH}:${RFS}/bin:${RFS}/sbin:${RFS}/usr/bin:${RFS}/usr/sbin:${PWD}/support

function source_compat_repos() {
	DCRFILE=''
	if [ -f ./DISTRO_COMPAT_REPOS-${DISTRO_BINARY_COMPAT}-${DISTRO_COMPAT_VERSION} ];then
		. ./DISTRO_COMPAT_REPOS-${DISTRO_BINARY_COMPAT}-${DISTRO_COMPAT_VERSION}
		DCRFILE="DISTRO_COMPAT_REPOS-${DISTRO_BINARY_COMPAT}-${DISTRO_COMPAT_VERSION}"
	else
		. ./DISTRO_COMPAT_REPOS-${DISTRO_BINARY_COMPAT}
		DCRFILE="DISTRO_COMPAT_REPOS-${DISTRO_BINARY_COMPAT}-${DISTRO_COMPAT_VERSION}"
	fi
}

function source_pkgs_specs() {
	DPSFILE=''
	if [ -f ./DISTRO_PKGS_SPECS-${DISTRO_BINARY_COMPAT}-${DISTRO_COMPAT_VERSION} ];then #w478
		. ./DISTRO_PKGS_SPECS-${DISTRO_BINARY_COMPAT}-${DISTRO_COMPAT_VERSION} #has FALLBACKS_COMPAT_VERSIONS
		DPSFILE="DISTRO_PKGS_SPECS-${DISTRO_BINARY_COMPAT}-${DISTRO_COMPAT_VERSION}"
	else
		. ./DISTRO_PKGS_SPECS-${DISTRO_BINARY_COMPAT} #has FALLBACKS_COMPAT_VERSIONS
		DPSFILE="DISTRO_PKGS_SPECS-${DISTRO_BINARY_COMPAT}"
	fi
}

function source_woofmergevars() {
	if [ -f WOOFMERGEVARS ];then
		. ./WOOFMERGEVARS #has variables WOOF_HOSTARCH, WOOF_TARGETARCH, WOOF_COMPATDISTRO, WOOF_COMPATVERSION
	else
		echo 'File WOOFMERGEVARS does not exist. This is created by script
	merge2out. Your setup is wrong, quiting.'
		exit 1
	fi
}

function set_binaries_var() {
	BINARIES='deb' #download to packages-deb.
	[ "$DISTRO_BINARY_COMPAT" = "slackware" ] && BINARIES="tgz_txz" #100617 download to packages-tgz_txz-${DISTRO_COMPAT_VERSION}.
	[ "$DISTRO_BINARY_COMPAT" = "slackware64" ] && BINARIES="tgz_txz" #140716 download to packages-tgz_txz-${DISTRO_COMPAT_VERSION}.
	[ "$DISTRO_BINARY_COMPAT" = "debian" ] && BINARIES="deb" #download to packages-deb-${DISTRO_COMPAT_VERSION}.
	[ "$DISTRO_BINARY_COMPAT" = "devuan" ] && BINARIES="deb" #download to packages-deb-${DISTRO_COMPAT_VERSION}.
	[ "$DISTRO_BINARY_COMPAT" = "gentoo" ] && BINARIES="gentoo" #120515 download to packages-gentoo-gap6
	[ "$DISTRO_BINARY_COMPAT" = "raspbian" ] && BINARIES="deb_raspbian" #download to packages-deb_raspbian-${DISTRO_COMPAT_VERSION}.
	BINARIES="${BINARIES}-${DISTRO_COMPAT_VERSION}" #w478
}

function set_archdir_var() {
	#debian and derivatives: wheezy and later
	#ubuntu and derivatives: precise and later
	ARCHDIR=''
	case $WOOF_COMPATDISTRO in raspbian|debian|devuan|ubuntu|trisquel)
		case $WOOF_TARGETARCH in #see file WOOFMERGEVARS
			x86) ARCHDIR='i386-linux-gnu' ;;
			x86_64) ARCHDIR='x86_64-linux-gnu' ;;
			arm) ARCHDIR='arm-linux-gnueabihf' ;;
		esac
	esac
}

function run_findpkgs() {
	#new script to find all pkgs for build...
	./support/findpkgs
	#...returns file status/findpkgs_FINAL_PKGS-${DISTRO_BINARY_COMPAT}-${DISTRO_COMPAT_VERSION}
	# each line is full db entry for pkg, prefixed with :generic-name:, pet/compat and repo-filename.
	# ex: :a52dec:|compat|Packages-puppy-wary5-official|a52dec-0.7.4-w5|a52dec|0.7.4-w5||BuildingBlock|68K||a52dec-0.7.4-w5.pet||A free ATSC A52 stream decoder|puppy|wary5||
	if [ $? -ne 0 ];then
		echo
		echo "ERROR: Script support/findpkgs aborted with an error, exiting."
		exit 1
	fi
	if [ ! -f status/findpkgs_FINAL_PKGS-${DISTRO_BINARY_COMPAT}-${DISTRO_COMPAT_VERSION} ];then
		echo
		echo "ERROR: Something went wrong with support/findpkgs, exiting."
		exit 1
	fi
}

function create_local_repos_dirs() {
	. ./WOOFMERGEVARS
	. ./DISTRO_SPECS
	#common dir to download pet pkgs to...
	mkdir -p ../local-repositories/${WOOF_TARGETARCH}/packages-pet
	[ ! -e packages-pet ] && ln -s ../local-repositories/${WOOF_TARGETARCH}/packages-pet packages-pet # check exist.
	set_binaries_var
	mkdir -p ../local-repositories/${WOOF_TARGETARCH}/packages-${BINARIES}
	[ ! -e packages-${BINARIES} ] && ln -s ../local-repositories/${WOOF_TARGETARCH}/packages-${BINARIES} packages-${BINARIES} # check exist.
	mkdir -p ../local-repositories/initrd-progs/0sources
	[ ! -e initrd-progs/0sources ] && ln -s ../../local-repositories/initrd-progs/0sources initrd-progs/0sources # check exist.
	if [ "$DISTRO_TARGETARCH" = "arm" ]; then
		mkdir -p ../local-repositories/${WOOF_TARGETARCH}/sd-skeleton-images
		[ ! -e sd-skeleton-images ] && ln -s ../local-repositories/${WOOF_TARGETARCH}/sd-skeleton-images sd-skeleton-images
	fi
	mkdir -p ../local-repositories/kernel-kit/sources
	[ ! -e kernel-kit/sources ] && ln -s ../../local-repositories/kernel-kit/sources kernel-kit/sources # check exist.
	mkdir -p ../local-repositories/kernel-kit/tools
	[ ! -e kernel-kit/tools ] && ln -s ../../local-repositories/kernel-kit/tools kernel-kit/tools # check exist.
}

function set_layer_type() { # sets $LAYER_TYPE
	LAYER_TYPE='aufs'
	modprobe aufs &>/dev/null
	cat /proc/filesystems | grep -q 'aufs' && return
	mount | grep ' / ' | grep -q 'aufs' && return
	lsmod | grep -q '^aufs ' && return
	#-
	LAYER_TYPE='overlay'
	modprobe overlay &>/dev/null
	cat /proc/filesystems | grep -q 'overlay' && return
	lsmod | grep -q '^overlay ' && return
	#-
	echo "ERROR: need aufs or overlay"
	exit 1
}

function clean_out_whiteouts() { #dir
	local dir="$@"
	# aufs whiteouts
	#find "$dir" -name '.wh*' -delete
	find "$dir" -name '.wh.*' -exec rm -rf '{}' 2>/dev/null \;
	# overlayfs whiteouts
	if [ "$LAYER_TYPE" = 'overlay' ]; then
		for ONE_CHAR_NODE in `find "$dir" -type c`
		do
			if [ "`stat -c '%t, %T' $ONE_CHAR_NODE`" = '0, 0' ]; then
				# paranoid test, regular files are also '0, 0'
				if [ "`stat -c '%F' $ONE_CHAR_NODE`" = 'character special file' ]; then
					rm $ONE_CHAR_NODE
				fi
			fi
		done
	fi
}

function merge_to_woof_out() {
	if [ -d "$1" ];then
	MERGE_DIRECTORY_NAME=${1##*/}
	if [ "$MERGE_DIRECTORY_NAME" = "patches" ]; then
		echo "Applying patches from ${1}..." | tee -a ${WOOF_OUT}/merge2out.log
		for PATCHFILE in \
		`find ${1} -mindepth 1 -maxdepth 1 -type f -iname '*.patch' | tr '\n' ' '`
		do
			echo "    $PATCHFILE" | tee -a ${WOOF_OUT}/merge2out.log
			PATCHFILE_PATH=$(realpath ${PATCHFILE})
			patch --unified --forward --silent -p 3 --input=${PATCHFILE_PATH} --directory=${WOOF_OUT} 2>&1 | tee -a ${WOOF_OUT}/merge2out.log
		done
	elif [ "$MERGE_DIRECTORY_NAME" = "packages-templates" -o "$MERGE_DIRECTORY_NAME" = "rootfs-packages" ]; then
		echo "Copying ${1}..." | tee -a ${WOOF_OUT}/merge2out.log
		for ONE_DIRECTORY in \
		`find ${1} -mindepth 1 -maxdepth 1 -type d | tr '\n' ' '`
		do
			DIRECTORY_NAME=${ONE_DIRECTORY##*/}
			echo "    $DIRECTORY_NAME" | tee -a ${WOOF_OUT}/merge2out.log
			if [ -n "$DIRECTORY_NAME" -a -d "${WOOF_OUT}/${MERGE_DIRECTORY_NAME}/${DIRECTORY_NAME}" ];then
				[ "$WOOF_OUT" != "" ] && rm -r ${WOOF_OUT}/${MERGE_DIRECTORY_NAME}/${DIRECTORY_NAME} 2>&1 | tee -a ${WOOF_OUT}/merge2out.log
			fi
			cp -a ${ONE_DIRECTORY} ${WOOF_OUT}/${MERGE_DIRECTORY_NAME}/ 2>&1 | tee -a ${WOOF_OUT}/merge2out.log
		done
	else
		echo "Copying ${1}..." | tee -a ${WOOF_OUT}/merge2out.log
		MERGE_DIRECTORY_FILES=`find ${1}/* \( -type f -or -type d -or -type l \) -printf '    %f\n'`
		if [ -n "$MERGE_DIRECTORY_FILES" ];then
			echo "$MERGE_DIRECTORY_FILES" | tee -a ${WOOF_OUT}/merge2out.log
			cp -a -f --remove-destination ${1}/* ${WOOF_OUT}/${MERGE_DIRECTORY_NAME}/ 2>&1 | tee -a ${WOOF_OUT}/merge2out.log
		fi
	fi
fi
}

#=========================================================================
#                           EXTRA ...
#=========================================================================

## you can use this after running ./support/findpkgs and ./1download
## to remove compat distro pkgs (deb,txz) that are no longer needed...
## sh _00func remove_unneeded_compat_pkgs
function remove_unneeded_compat_pkgs() {
	. ./DISTRO_SPECS
	create_local_repos_dirs
	case $DISTRO_BINARY_COMPAT in
		raspbian|debian|devuan|ubuntu|trisquel) W='.*\.deb' ;;
		slackware*) W='.*\.txz|.*\.tgz' ;;
		*) echo "Not supported: $DISTRO_BINARY_COMPAT" ;;
	esac
	if [ ! -f status/findpkgs_FINAL_PKGS-${DISTRO_BINARY_COMPAT}-${DISTRO_COMPAT_VERSION} ];then
		echo "MISSING FILE: status/findpkgs_FINAL_PKGS-${DISTRO_BINARY_COMPAT}-${DISTRO_COMPAT_VERSION}"
		return 1
	fi
	grep -E -o ${W} status/findpkgs_FINAL_PKGS-${DISTRO_BINARY_COMPAT}-${DISTRO_COMPAT_VERSION} | \
	sed 's%.*|%%' > /tmp/compatpkgs$$
	if [ ! -d packages-${BINARIES}/zzzzz ] ; then
		mkdir -p packages-${BINARIES}/zzzzz
		cat /tmp/compatpkgs$$ | while read file ; do
			if [ -f packages-${BINARIES}/${file} ] ; then
				mv packages-${BINARIES}/${file} packages-${BINARIES}/zzzzz
			fi
		done
		rm -f packages-${BINARIES}/* 2>/dev/null
		mv packages-${BINARIES}/zzzzz/* packages-${BINARIES}/
		rm -rf packages-${BINARIES}/zzzzz
	fi
	rm -f /tmp/compatpkgs$$
}

if [ "${0##*/}" = "_00func" ] ; then
	$@
fi

### END ###
